import { request } from '@umijs/max';

// 错误日志接口类型定义
export interface ErrorLog {
  id: string;
  project: string;
  project_name?: string;
  level: 'error' | 'warning' | 'info' | 'debug';
  message: string;
  stack_trace?: string;
  user_agent?: string;
  ip_address?: string;
  url?: string;
  timestamp: string;
  fingerprint?: string;
  count?: number;
  firstSeen?: string;
  lastSeen?: string;
  source?: string;
  user_id?: string;  // 改为 user_id
  session_id?: string;  // 改为 session_id
  request_info?: {  // 改为 request_info
    method: string;
    url: string;
    params: any;
    headers: any;
    responseStatus: number;
    responseTime: number;
  };
  breadcrumbs?: Array<{
    timestamp: string;
    category: string;
    message: string;
    level: string;
    data?: any;
  }>;
  performance?: {
    memoryUsage: number;
    cpuUsage: number;
    loadTime: number;
    renderTime: number;
  };
  context?: {
    variables: any;
    state: any;
    props: any;
  };
}

export interface DashboardStats {
  totalErrors: number;
  errorRate: number;
  affectedUsers: number;
  avgResponseTime: number;
  errorTrend: Array<{ time: string; count: number }>;
  topErrors: Array<{ message: string; count: number; trend: 'up' | 'down' | 'stable' }>;
  browserStats: Array<{ name: string; count: number; percentage: number }>;
  errorsByLevel: { error: number; warning: number; info: number; debug: number };
}

export interface ErrorTrendData {
  time: string;
  errorCount: number;
  errorRate: number;
  type: string;
}

export interface ErrorLogParams {
  project?: string;
  level?: string;
  search?: string;
  page?: number;
  page_size?: number;
  ordering?: string;
  start_time?: string;
  end_time?: string;
}

// 获取错误日志列表
export async function getErrorLogs(params: ErrorLogParams = {}) {
  return request<{
    success: boolean;
    data: {
      results: ErrorLog[];
      count: number;
      next?: string;
      previous?: string;
    };
  }>('/api/logs/errors/', {
    method: 'GET',
    params,
  });
}

// 获取错误日志统计信息
export async function getErrorLogStats(projectId?: string) {
  const params = projectId ? { project: projectId } : {};
  return request<{
    success: boolean;
    data: {
      total: number;
      by_level: Array<{ level: string; count: number }>;
      recent_trend: Array<{ time: string; count: number }>;
      top_errors: Array<{ message: string; count: number }>;
      browser_stats: Array<{ browser: string; count: number }>;
    };
  }>('/api/logs/errors/stats/', {
    method: 'GET',
    params,
  });
}

// 获取仪表板统计数据
export async function getDashboardStats(projectId?: string): Promise<DashboardStats> {
  const params = projectId ? { project: projectId } : {};
  const response = await request<{
    success: boolean;
    code: number;
    data: DashboardStats;
    message: string;
  }>('/api/logs/errors/dashboard/', {
    method: 'GET',
    params,
  });
  
  // 检查响应格式
  if (response.success && response.data) {
    return response.data;
  } else {
    // 如果后端还没有更新为统一格式，临时兼容处理
    return response as any;
  }
}

// 获取错误趋势数据
export async function getErrorTrend(params: {
  projectId?: string;
  timeRange: string;
  metric: string;
}) {
  return request<{
    success: boolean;
    data: ErrorTrendData[];
  }>('/api/logs/errors/trend/', {
    method: 'GET',
    params: {
      project: params.projectId,
      time_range: params.timeRange,
      metric: params.metric,
    },
  });
}

// 获取错误详情
export async function getErrorLogDetail(id: string) {
  return request<{
    success: boolean;
    data: ErrorLog;
  }>(`/api/logs/errors/${id}/`, {
    method: 'GET',
  });
}

// 创建错误日志
export async function createErrorLog(data: Partial<ErrorLog>) {
  return request<{
    success: boolean;
    data: ErrorLog;
  }>('/api/logs/errors/', {
    method: 'POST',
    data,
  });
}

// 批量删除错误日志
export async function deleteErrorLogs(ids: string[]) {
  return request<{
    success: boolean;
    message: string;
  }>('/api/logs/errors/batch_delete/', {
    method: 'POST',
    data: { ids },
  });
}

// 获取实时错误数据（WebSocket或轮询）
export async function getRealTimeErrors(projectId?: string) {
  const params = projectId ? { project: projectId } : {};
  return request<{
    success: boolean;
    data: ErrorLog[];
  }>('/api/logs/errors/realtime/', {
    method: 'GET',
    params,
  });
}